package com.chaowen.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.os.Handler;
import android.os.Message;

import com.chaowen.model.UserInfo;
import com.chaowen.util.SocketCreate;

public class SignTask extends Task{
	private Handler handler;
	private String studentid;//学生学号
	private String signedTime;//签到时间
	private int signState;//签到状态

	@Override
	public void onPostExecute(int result) {
		Message msg = handler.obtainMessage();
		switch (result) {
		case 22:
			msg.what = 22;
			handler.sendMessage(msg);
			UserInfo.isSign = false;
			break;
		case 21:
			msg.what = 21;
			handler.sendMessage(msg);
			UserInfo.isSign = true;
			break;
		case 20:
			msg.what = 21;
			handler.sendMessage(msg);
			UserInfo.isSign = true;
			break;
		case -1:
			msg.what = -1;
			handler.sendMessage(msg);
			UserInfo.isSign = false;
			break;
		case 3:
			msg.what = 3;
			handler.sendMessage(msg);
			UserInfo.isSign = false;
			break;
		}
	}

	@Override
	public void execute() {
		studentid = UserInfo.userName;
		signedTime = getNowTime();
		Thread t = new Thread(SignTask.this);
		t.start();
	}
	
	private String getNowTime() {
		Date date = new Date();
		DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//		dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
		return dateFormat.format(date.getTime());
	}

	@Override
	public void run() {
		Socket socket = null;
		try {
			socket = SocketCreate.createSocket();
			BufferedReader reader = SocketCreate.getReader(socket);
			PrintWriter writer = SocketCreate.getWriter(socket);
			System.out.println("发送给服务器的：" + studentid +"   "+signedTime);
			writer.println("sign," + studentid +","+signedTime);
			String get = reader.readLine();
			System.out.println("get---->" + get);
			signState = Integer.parseInt(get);
			System.out.println("签到" + signState);
			onPostExecute(signState);
			System.out.println("socketstate: " + socket.isClosed());
		} catch (Exception e) {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			onPostExecute(3);
			e.printStackTrace();
		}
	}

	@Override
	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	
}
